/**
 * Created by yunpeng on 2015/4/11.
 */
starterModule.directive('ngCropper',['$http','$compile','$state','CropperService',function($http,$compile,$state,CropperService){//自定义指令
    return{
        restrict: 'A',//
        link:function(scope,element,attrs,controller){
            scope.umsg=false;
            scope.upLoad = function(){
                scope.umsg=true;
                if(!file){
                    document.getElementById('progress').innerHTML = '请选择图片';
                    setTimeout(function(){
                        scope.umsg=false;
                        scope.$apply();
                    },3000);
                    return;
                }
                scope.umsg=true;
                document.getElementById('progress').innerHTML = '图片正在上传...';
                var fd = new FormData();
                fd.append("name", "图片");
                fd.append("files", file);

                //scope.$apply();

                var xhr = new XMLHttpRequest();
                if(scope.urltype=='upheader'){
                    fd.append('scale1',$('#dataX').val());
                    fd.append('scale2',$('#dataY').val());
                    fd.append('width',$('#dataWidth').val());
                    fd.append('height',$('#dataHeight').val());
                    xhr.open("POST" ,"/users/uploadHeaderFiles" , true);
                }else{
                    xhr.open("POST" ,"/uploadFiles" , true);
                }

                xhr.setRequestHeader('Authorization','Bearer ' +  localStorage.getItem('token'))//$window.sessionStorage.token
                //alert(xhr.upload.onprogress)
                xhr.upload.addEventListener("progress", function(evt){
                        //alert(0)
                    if (evt.lengthComputable) {
                        var percentComplete = Math.round(evt.loaded * 100 / evt.total);
                        document.getElementById('progress').innerHTML = '正在上传... '+percentComplete.toString() + '%';
                    }


                }, false);
                /*xhr.upload.onprogress = function(evt){
                        alert(0)
                    if (evt.lengthComputable) {
                        var percentComplete = Math.round(evt.loaded * 100 / evt.total);
                        document.getElementById('progress').innerHTML = '正在上传... '+percentComplete.toString() + '%';
                    }


                }*/
                xhr.send(fd);
                xhr.onload = function(e) {
                    if (this.status == 200) {
                        //文件上传完成
                        var filename = this.responseText;
                        document.getElementById('progress').innerHTML = '图片已上传完成...'
                            setTimeout(function(){
                            if(scope.urltype=='transfer'){
                                CropperService.getCropperdata()[0] = {
                                    scale1:$('#dataX').val(),
                                    scale2:$('#dataY').val(),
                                    width:$('#dataWidth').val(),
                                    height:$('#dataHeight').val(),
                                    filename:filename,
                                    filepath:filename.substring(0,10)+'.jpg'
                                };
                                $state.go('tab.transferAddCar');
                            }else{
                               var user = JSON.parse(localStorage.getItem('user'));
                                user.headerpath = filename;
                                //alert( user.headerpath);
                                localStorage.setItem('user',JSON.stringify(user));
                                $state.go('tab.center');
                            }
                        },2000);

                    }
                };
            }

            $('.eg-wrapper').css('height',$(window).height()-88+'px');
            var $image = $(".cropper"),
                $dataX = $("#dataX"),
                $dataY = $("#dataY"),
                $dataHeight = $("#dataHeight"),
                $dataWidth = $("#dataWidth"),
                console = window.console || {log:$.noop},
                cropper,
                file;

            $image.cropper({
                aspectRatio: scope.scale1 / scope.scale2,
                // autoCropArea: 1,
                data: {
                    x: 80,
                    y: 60,
                    width: scope.width,
                    height:scope.height
                },
                //preview: ".preview",

                // multiple: true,
                // autoCrop: false,
                // dragCrop: false,
                // dashed: false,
                // modal: false,
                // movable: false,
                // resizable: false,
                // zoomable: false,
                // rotatable: false,
                // checkImageOrigin: false,

                // maxWidth: 480,
                // maxHeight: 270,
                // minWidth: 160,
                // minHeight: 90,

                done: function(data) {
                    /*$dataX.val(data.x);
                     $dataY.val(data.y);
                     $dataHeight.val(data.height);
                     $dataWidth.val(data.width);*/
                    $dataX.val(Math.round(data.x));
                    $dataY.val(Math.round(data.y));
                    $dataHeight.val(Math.round(data.height));
                    $dataWidth.val(Math.round(data.width));
                },

                build: function(e) {
                    console.log(e.type);
                },

                built: function(e) {
                    console.log(e.type);
                },

                dragstart: function(e) {
                    console.log(e.type);
                },

                dragmove: function(e) {
                    console.log(e.type);
                },

                dragend: function(e) {
                    console.log(e.type);
                }
            });

            cropper = $image.data("cropper");

            $image.on({
                "build.cropper": function(e) {
                    console.log(e.type);
                    // e.preventDefault();
                },
                "built.cropper": function(e) {
                    console.log(e.type);
                    // e.preventDefault();
                },
                "dragstart.cropper": function(e) {
                    console.log(e.type);
                    // e.preventDefault();
                },
                "dragmove.cropper": function(e) {
                    console.log(e.type);
                    // e.preventDefault();
                },
                "dragend.cropper": function(e) {
                    console.log(e.type);
                    // e.preventDefault();
                }
            });

            $("#reset").click(function() {
                $image.cropper("reset");
            });

            $("#reset2").click(function() {
                $image.cropper("reset", true);
            });

            $("#clear").click(function() {
                $image.cropper("clear");
            });

            $("#destroy").click(function() {
                $image.cropper("destroy");
            });

            $("#enable").click(function() {
                $image.cropper("enable");
            });

            $("#disable").click(function() {
                $image.cropper("disable");
            });

            $("#zoom").click(function() {
                $image.cropper("zoom", $("#zoomWith").val());
            });

            $("#zoomIn").click(function() {
                $image.cropper("zoom", 0.1);
            });

            $("#zoomOut").click(function() {
                $image.cropper("zoom", -0.1);
            });

            $("#rotate").click(function() {
                $image.cropper("rotate", $("#rotateWith").val());
            });

            $("#rotateLeft").click(function() {
                $image.cropper("rotate", -90);
            });

            $("#rotateRight").click(function() {
                $image.cropper("rotate", 90);
            });

            var $inputImage = $("#inputImage");

            if (window.FileReader) {
                $inputImage.change(function() {
                    var fileReader = new FileReader(),
                        files = this.files;
                        //file;

                    if (!files.length) {
                        return;
                    }

                    file = files[0];

                    if (/^image\/\w+$/.test(file.type)) {
                        fileReader.readAsDataURL(file);
                        fileReader.onload = function () {
                            $image.cropper("reset", true).cropper("replace", this.result);
                            $inputImage.val("");
                        };
                    } else {
                        showMessage("Please choose an image file.");
                    }
                });
            } else {
                $inputImage.addClass("hide");
            }

            $("#setAspectRatio").click(function() {
                $image.cropper("setAspectRatio", $("#aspectRatio").val());
            });

            $("#replace").click(function() {
                $image.cropper("replace", $("#replaceWith").val());
            });

            $("#getImageData").click(function() {
                $("#showImageData").val(JSON.stringify($image.cropper("getImageData")));
            });

            $("#setData").click(function() {
                $image.cropper("setData", {
                    x: $dataX.val(),
                    y: $dataY.val(),
                    width: $dataWidth.val(),
                    height: $dataHeight.val()
                });
            });

            $("#getData").click(function() {
                $("#showData").val(JSON.stringify($image.cropper("getData")));
            });

            $("#getData2").click(function() {
                $("#showData").val(JSON.stringify($image.cropper("getData", true)));
            });

            $("#getDataURL").click(function() {
                var dataURL = $image.cropper("getDataURL");

                $("#dataURL").text(dataURL);
                $("#showDataURL").html('<img src="' + dataURL + '">');
            });

            $("#getDataURL2").click(function() {
                var dataURL = $image.cropper("getDataURL", "image/jpeg");

                $("#dataURL").text(dataURL);
                $("#showDataURL").html('<img src="' + dataURL + '">');
            });

            $("#getDataURL3").click(function() {
                var dataURL = $image.cropper("getDataURL", {
                    width: 160,
                    height: 90
                });

                $("#dataURL").text(dataURL);
                $("#showDataURL").html('<img src="' + dataURL + '">');
            });
        }
    }
}]);